package com.tbb.app.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbb.app.base.entity.Follow;
import com.tbb.app.base.mapper.FollowMapper;
import com.tbb.app.base.service.IFollowService;
import com.tbb.app.common.service.CurrentLoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户关注关系表 服务实现类
 *
 * @author Liu
 * @since 2022-01-11
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private CurrentLoginUserService currentLoginUserService;

    @Override
    public void follow(String followedId, int type) {
        String userId = currentLoginUserService.getUserId(true);
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Follow::getFollowedId, followedId)
                .eq(Follow::getFollowerId, userId);
        if (type == 1) {
            if (this.count(wrapper) <= 0) {
                Follow follow = new Follow();
                follow.setFollowedId(followedId)
                        .setFollowerId(userId);
                this.save(follow);
            }
        } else {
            this.remove(wrapper);
        }
    }

    @Override
    public Boolean isFollowed(String userId, String followedId) {
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Follow::getFollowedId, followedId)
                .eq(Follow::getFollowerId, userId);
        return this.count(wrapper) > 0;
    }

    @Override
    public long countFollow(String userId) {
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Follow::getFollowerId, userId);
        return this.count(wrapper);
    }

    @Override
    public long countFollower(String userId) {
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Follow::getFollowedId, userId);
        return this.count(wrapper);
    }

    @Override
    public List<String> listByFollowerId(String userId) {
        QueryWrapper<Follow> wrapper = new QueryWrapper<>();
        wrapper.lambda().select(Follow::getFollowedId)
                .eq(Follow::getFollowerId, userId)
                .ne(Follow::getFollowedId, userId);
        return this.list(wrapper).stream().map(Follow::getFollowedId).collect(Collectors.toList());
    }
}
